// pages/admin-detail/admin-detail.js
const api = require('../../utils/api.js')
const util = require('../../utils/util.js')
const app = getApp()

Page({
    data: {
        orderId: '',
        orderInfo: {},
        statusText: {
            pending: '待处理',
            processing: '处理中',
            completed: '已完成',
            rejected: '已拒绝'
        },
        statusClass: {
            pending: 'status-pending',
            processing: 'status-processing',
            completed: 'status-completed',
            rejected: 'status-rejected'
        },
        statusOptions: [
            { value: 'processing', label: '开始处理' },
            { value: 'completed', label: '已完成' },
            { value: 'rejected', label: '拒绝处理' }
        ],
        statusIndex: -1,
        newStatus: '',
        feedback: '',
        submitting: false,
        // 学生指派相关
        showAssignModal: false,
        students: [],
        assignedStudentName: '',
        // 备件相关
        showPartsModal: false,
        availableParts: [],
        usedParts: []
    },

    onLoad(options) {
        options = options || {}
        // 允许管理员和学生访问
        if (!app.globalData.isAdmin && app.globalData.userRole !== 'student') {
            wx.showToast({
                title: '权限不足',
                icon: 'none',
                duration: 2000
            })
            setTimeout(() => {
                wx.navigateBack()
            }, 2000)
            return
        }

        if (options.orderId) {
            this.setData({ orderId: options.orderId })
            this.loadOrderDetail(options.orderId)
        }
    },

    // 加载工单详情
    loadOrderDetail(orderId) {
        wx.showLoading({ title: '加载中...' })

        api.getRepairOrderDetail(orderId).then(res => {
            // 格式化时间
            res.created_at = util.formatTime(util.safeDate(res.created_at))
            if (res.updated_at) {
                res.updated_at = util.formatTime(util.safeDate(res.updated_at))
            }

            // 处理图片数组
            if (typeof res.images === 'string') {
                res.images = JSON.parse(res.images)
            }

            this.setData({
                orderInfo: res,
                usedParts: res.spareParts || []
            })
        }).catch(err => {
            console.error('加载工单详情失败', err)

            wx.showModal({
                title: '加载失败',
                content: '工单不存在或已删除',
                showCancel: false,
                success: () => {
                    wx.navigateBack()
                }
            })
        }).finally(() => {
            wx.hideLoading()
        })
    },

    // 状态选择
    onStatusChange(e) {
        const index = parseInt(e.detail.value)
        this.setData({
            statusIndex: index,
            newStatus: this.data.statusOptions[index].value
        })
    },

    // 反馈输入
    onFeedbackInput(e) {
        this.setData({
            feedback: e.detail.value
        })
    },

    // 预览图片
    previewImage(e) {
        const url = e.currentTarget.dataset.url

        wx.previewImage({
            current: url,
            urls: this.data.orderInfo.images
        })
    },

    // 拨打电话
    callPhone() {
        if (this.data.orderInfo.phone) {
            wx.makePhoneCall({
                phoneNumber: this.data.orderInfo.phone
            })
        }
    },

    // 验证表单
    validate() {
        if (this.data.statusIndex < 0) {
            wx.showToast({
                title: '请选择处理状态',
                icon: 'none'
            })
            return false
        }

        if (this.data.newStatus === 'completed' && !this.data.feedback.trim()) {
            wx.showToast({
                title: '完成工单需要填写处理反馈',
                icon: 'none'
            })
            return false
        }

        return true
    },

    // 提交处理
    submitHandle() {
        // 验证表单
        if (!this.validate()) {
            return
        }

        // 防止重复提交
        if (this.data.submitting) {
            return
        }

        wx.showModal({
            title: '确认提交',
            content: `确定要将工单状态更新为"${this.data.statusOptions[this.data.statusIndex].label}"吗？`,
            success: res => {
                if (res.confirm) {
                    this.doSubmit()
                }
            }
        })
    },

    // 执行提交
    async doSubmit() {
        this.setData({ submitting: true })
        wx.showLoading({ title: '提交中...' })

        try {
            const updateData = {
                status: this.data.newStatus,
                feedback: this.data.feedback,
                adminOpenid: app.globalData.openid,
                adminName: app.globalData.userInfo?.nickName || '管理员'
            }

            await api.updateRepairOrder(this.data.orderId, updateData)

            wx.hideLoading()

            wx.showToast({
                title: '处理成功',
                icon: 'success',
                duration: 2000
            })

            // 延迟返回
            setTimeout(() => {
                wx.navigateBack()
            }, 2000)

        } catch (err) {
            wx.hideLoading()
            console.error('提交处理失败', err)

            wx.showModal({
                title: '提交失败',
                content: err.message || '网络错误，请稍后重试',
                showCancel: false
            })
        } finally {
            this.setData({ submitting: false })
        }
    },

    // ==========================================
    // 学生指派功能
    // ==========================================

    // 显示指派弹窗
    showAssignModal() {
        this.loadStudents()
        this.setData({ showAssignModal: true })
    },

    // 隐藏指派弹窗
    hideAssignModal() {
        this.setData({ showAssignModal: false })
    },

    // 停止冒泡
    stopPropagation() { },

    // ========== 备件相关函数 ==========

    // 显示备件选择弹窗
    async showPartsModal() {
        try {
            const res = await api.request({ url: '/spare-parts' })
            if (res.list) {
                this.setData({
                    availableParts: res.list.map(p => ({ ...p, useQty: 1 })),
                    showPartsModal: true
                })
            }
        } catch (error) {
            wx.showToast({ title: '加载备件失败', icon: 'none' })
        }
    },

    // 隐藏备件选择弹窗
    hidePartsModal() {
        this.setData({ showPartsModal: false })
    },

    // 输入备件数量
    onPartQtyInput(e) {
        const id = e.currentTarget.dataset.id
        const value = parseInt(e.detail.value) || 1
        const parts = this.data.availableParts
        const index = parts.findIndex(p => p.id === id)
        if (index >= 0) {
            parts[index].useQty = value
            this.setData({ availableParts: parts })
        }
    },

    // 添加备件到使用列表
    async addPart(e) {
        const part = e.currentTarget.dataset.part
        const quantity = part.useQty || 1

        if (quantity > part.current_stock) {
            wx.showToast({ title: '库存不足', icon: 'none' })
            return
        }

        try {
            const res = await api.request({
                url: '/repair/use-spare-part',
                method: 'POST',
                data: {
                    repairOrderId: this.data.orderId,
                    partId: part.id,
                    quantity: quantity,
                    operatorOpenid: app.globalData.openid,
                    operatorName: app.globalData.userInfo?.nickName || '管理员'
                }
            })

            // api.request 成功返回即代表 code=0，且会自动解包 data
            wx.showToast({ title: '添加成功', icon: 'success' })

            // 更新已使用备件列表
            const usedParts = this.data.usedParts
            usedParts.push({
                id: res.id, // 解包后的数据直接包含 id
                part_id: part.id,
                name: part.name,
                quantity: quantity
            })
            this.setData({ usedParts })

            // 刷新可用备件列表
            this.loadAvailableParts()

        } catch (error) {
            console.error('添加备件失败', error)
            wx.showToast({ title: error.message || '操作失败', icon: 'none' })
        }
    },

    // 移除备件
    removePart(e) {
        const id = e.currentTarget.dataset.id
        const index = e.currentTarget.dataset.index

        wx.showModal({
            title: '确认移除',
            content: '确定要移除该备件吗？库存将自动恢复。',
            success: async (res) => {
                if (res.confirm) {
                    try {
                        const result = await api.removeSparePart(this.data.orderId, id)
                        if (result.code === 0) {
                            wx.showToast({ title: '移除成功', icon: 'success' })

                            const usedParts = this.data.usedParts
                            usedParts.splice(index, 1)
                            this.setData({ usedParts })

                            // 刷新可用备件列表（库存已更新）
                            if (this.data.showPartsModal) {
                                this.loadAvailableParts()
                            }
                        } else {
                            wx.showToast({ title: result.message || '移除失败', icon: 'none' })
                        }
                    } catch (error) {
                        console.error('移除备件失败', error)
                        wx.showToast({ title: '移除失败', icon: 'none' })
                    }
                }
            }
        })
    },

    // 加载可用备件
    async loadAvailableParts() {
        try {
            const res = await api.request({ url: '/spare-parts' })
            if (res.list) {
                this.setData({
                    availableParts: res.list.map(p => ({ ...p, useQty: 1 }))
                })
            }
        } catch (error) {
            console.error('加载备件失败:', error)
        }
    },

    // 加载学生列表
    async loadStudents() {
        try {
            wx.showLoading({ title: '加载学生...' })
            const data = await api.request({
                url: '/students',
                data: { teacherId: app.globalData.openid }
            })

            if (!data.list || data.list.length === 0) {
                wx.hideLoading()
                wx.showToast({
                    title: '暂无学生，请先在管理后台设置',
                    icon: 'none',
                    duration: 3000
                })
                return
            }

            this.setData({ students: data.list })
            wx.hideLoading()
        } catch (error) {
            wx.hideLoading()
            console.error('加载学生列表失败', error)
            wx.showToast({
                title: '加载失败',
                icon: 'none'
            })
        }
    },

    // 选择学生
    selectStudent(e) {
        const { openid, name } = e.currentTarget.dataset

        wx.showModal({
            title: '确认指派',
            content: `确定将此工单指派给 ${name} 吗？`,
            success: res => {
                if (res.confirm) {
                    this.assignToStudent(openid, name)
                }
            }
        })
    },

    // 指派工单给学生
    async assignToStudent(studentOpenid, studentName) {
        try {
            wx.showLoading({ title: '指派中...' })

            await api.request({
                url: '/admin/assign-order',
                method: 'POST',
                data: {
                    orderId: this.data.orderId,
                    studentOpenid: studentOpenid,
                    teacherOpenid: app.globalData.openid
                }
            })

            wx.hideLoading()
            wx.showToast({
                title: '指派成功',
                icon: 'success',
                duration: 2000
            })

            this.setData({
                showAssignModal: false,
                assignedStudentName: studentName,
                'orderInfo.assigned_to': studentOpenid
            })

            // 刷新工单详情
            setTimeout(() => {
                this.loadOrderDetail(this.data.orderId)
            }, 1000)

        } catch (error) {
            wx.hideLoading()
            console.error('指派失败', error)
            wx.showToast({
                title: error.message || '指派失败',
                icon: 'none'
            })
        }
    }
})
